package br.xraylol;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Mode;

public class Process {
	private int w;
	private int h;
	private int limite = 100;
	private float percentScale = 1.0f;
	private int timeWaitProcess = 200;

	public void startProcess(File img) {
		List<String> nameList = new ArrayList<String>();
		try {
			BufferedImage buffImg = ImageIO.read(img);

			float[] widths = { 0.1375f, 0.2875f, 0.43125f, 0.578125f, 0.725f,
					0.1375f, 0.2875f, 0.43125f, 0.578125f, 0.725f };
			float[] heights = { 0.385555555556f, 0.895f };

			float widthField = 0.1375f;
			float heightField = 0.025555555556f;
			w = buffImg.getWidth();
			h = buffImg.getHeight();
			for (int i = 0, j = 0; i < 10; i++) {
				BufferedImage heroNameImg = buffImg.getSubimage(
						(int) Math.round(w * widths[i]),
						(int) Math.round(h * heights[j]),
						(int) Math.round(w * widthField),
						(int) Math.round(h * heightField));
				BufferedImage scaledImg = Scalr.resize(heroNameImg,
						Mode.AUTOMATIC, (int) Math.round(w * percentScale),
						(int) Math.round(h * percentScale), null);
				File savedFile = save(scaledImg);
				String heroName = null;
				try {
					heroName = callTesseract(savedFile.getPath());
					nameList.add(heroName);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (i == 4) {
					j++;
				}
			}
			for(String s:nameList){
				System.out.println(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unused")
	private BufferedImage scale(BufferedImage sbi, int imageType, int dWidth,
			int dHeight, double fWidth, double fHeight) {
		BufferedImage dbi = null;
		if (sbi != null) {
			dbi = new BufferedImage(dWidth, dHeight, imageType);
			Graphics2D g = dbi.createGraphics();
			AffineTransform at = AffineTransform.getScaleInstance(fWidth,
					fHeight);
			g.drawRenderedImage(sbi, at);
		}
		return dbi;
	}

	private File save(BufferedImage buffImg) {
		trataImage(buffImg);

		Calendar c = new GregorianCalendar();
		File outputfile = new File("G:/lolPrint/img" + c.getTimeInMillis()
				+ ".png");
		try {
			ImageIO.write(buffImg, "png", outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outputfile;
	}

	@SuppressWarnings("unused")
	private String readImgOCR(BufferedImage buffImg) {
		return "";
	}

	@SuppressWarnings("unused")
	private String readImgOCR(File buffImg) {
		//Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping

		//try {
			//String result = instance.doOCR(buffImg);
			//System.out.println(result);
		//} catch (TesseractException e) {
		//	System.err.println(e.getMessage());
		//}

		return "";
	}

	private BufferedImage trataImage(BufferedImage buffImg) {
		// boolean lineHasWhite = false;
		for (int i = 0; i < buffImg.getHeight(); i++) {
			// lineHasWhite = false;
			for (int j = 0; j < buffImg.getWidth(); j++) {
				Color c = new Color(buffImg.getRGB(j, i));
				if (c.getBlue() < limite || c.getRed() < limite
						|| c.getGreen() < limite) {
					Color cc = new Color(0);
					buffImg.setRGB(j, i, cc.getRGB());
				} else {
					Color cc = new Color(255, 255, 255);
					buffImg.setRGB(j, i, cc.getRGB());
					// lineHasWhite = true;
				}
				/*
				 * if (!(i < buffImg.getHeight() - 1) && !lineHasWhite) {
				 * BufferedImage scaledImg = Scalr.resize(buffImg,
				 * Mode.AUTOMATIC, 0, i+1, null); }
				 */
			}
		}
		return buffImg;
	}

	@SuppressWarnings("unused")
	private String callTesseract(String img) throws InterruptedException,
			IOException {
		String path = System.getProperty("user.dir");
		Calendar c = new GregorianCalendar();
		String t = c.getTimeInMillis() + "";
		java.lang.Process p = Runtime.getRuntime().exec(
				"cmd /c start " + path + "/tesseract/tesseract.exe " + img
						+ " " + path + "/tesseract/tmp" + t);
		Thread.sleep(timeWaitProcess);
		File file = new File(path + "/tesseract/tmp" + t + ".txt");
		InputStream is = new FileInputStream(file);
		String ret = getStringFromInputStream(is);
		file.delete();
		return ret;
	}

	private static String getStringFromInputStream(InputStream is) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();

		String line;
		try {

			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return sb.toString();

	}
}
